package com.onlyphoto.onlymall.mvp.view.adapter

import android.annotation.SuppressLint
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
import com.onlyphoto.onlymall.R
import com.onlyphoto.onlymall.bean.response.CouponBean
import com.onlyphoto.onlymall.events.ReceiveEvent
import org.greenrobot.eventbus.EventBus
import java.util.ArrayList

/**
 * Created by gaochujia on 2019-08-27.
 */

class CouponAdapter : RecyclerView.Adapter<RecyclerView.ViewHolder>() {

    private var mList = arrayListOf<CouponBean>()
    private var listener: OnItemClickListener? = null

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder {
        val item = LayoutInflater.from(parent.context).inflate(
                R.layout.item_coupon, parent, false)
        return CouponItemHolder(item)
    }

    override fun getItemCount(): Int {
        return mList.size
    }

    override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
        (holder as CouponItemHolder).loadData(mList[position])
        holder.itemView.setOnClickListener{
            listener?.click(mList[position].id, mList[position].name, mList[position].value)
        }
    }

    fun setItemData(list: ArrayList<CouponBean>) {
        this.mList = list
        notifyDataSetChanged()
    }

    class CouponItemHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {

        var price: TextView? = null
        var condition: TextView? = null
        var couponName: TextView? = null
        var date: TextView? = null
        var btnFeatures: TextView? = null

        init {
            price = itemView.findViewById(R.id.price)
            condition = itemView.findViewById(R.id.condition)
            couponName = itemView.findViewById(R.id.coupon_name)
            date = itemView.findViewById(R.id.date)
            btnFeatures = itemView.findViewById(R.id.btn_features)
        }

        @SuppressLint("SetTextI18n")
        fun loadData(couponBean: CouponBean) {
            price?.text = "¥ " + couponBean.value
            condition?.text = "满" + couponBean.condition + "可用"
            couponName?.text = couponBean.title
            date?.text = couponBean.start_ymd + "-" + couponBean.end_ymd
            if (couponBean.isStore) {
                btnFeatures?.text = "领取"
                btnFeatures?.setOnClickListener{
                    EventBus.getDefault().post(ReceiveEvent(couponBean.id, couponBean.end_tm))
                }
            }
        }
    }

    fun setOnItemClickListener(listener: OnItemClickListener){
        this.listener = listener
    }

    interface OnItemClickListener{
        fun click(id: Int, name: String, price: Double)
    }
}